import { TokenType } from '@/api/login/types';
import { decrypt, encrypt } from '@/utils/jsencrypt';
import { Local } from '@/utils/storage';

const AccessTokenKey = 'ACCESS_TOKEN';
const RefreshTokenKey = 'REFRESH_TOKEN';

// 获取token
export const getAccessToken = () => {
  // 此处与TokenKey相同，此写法解决初始化时Cookies中不存在TokenKey报错
  return Local.get(AccessTokenKey) ? Local.get(AccessTokenKey) : Local.get('ACCESS_TOKEN');
};

// 刷新token
export const getRefreshToken = () => {
  return Local.get(RefreshTokenKey);
};

// 设置token
export const setToken = (token: TokenType) => {
  Local.set(RefreshTokenKey, token.refreshToken);
  Local.set(AccessTokenKey, token.accessToken);
};

// 删除token
export const removeToken = () => {
  Local.set(AccessTokenKey, '');
  Local.set(RefreshTokenKey, '');
};

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return 'Bearer ' + token;
};
// ========== 账号相关 ==========

export type LoginFormType = {
  tenantName: string;
  username: string;
  password: string;
  rememberMe: boolean;
};

export const getLoginForm = () => {
  const loginForm: LoginFormType = Local.get('loginForm');
  if (loginForm) {
    loginForm.password = decrypt(loginForm.password) as string;
  }
  return loginForm;
};

export const setLoginForm = (loginForm: LoginFormType) => {
  loginForm.password = encrypt(loginForm.password) as string;
  Local.set('loginForm', '');
};

export const removeLoginForm = () => {
  Local.set('loginForm', '');
};
